package vip.meeet.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import vip.meeet.bean.TableBean;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

@Controller
@RequestMapping("/table")
public class TableController {

    private static final String ROOT = "D:\\mydata";

    @RequestMapping("/bean")
    public String bean(Model model){
        LinkedList<String> headers = new LinkedList<>();
        headers.add("v1");
        headers.add("v2");
        headers.add("v3");

        LinkedList<TableBean> datas = new LinkedList<>();
        for(int i=0;i<20;i++){
            TableBean tableBean = new TableBean();
            tableBean.setV0(i);
            tableBean.setV1(i * 2);
            tableBean.setV3(i * 3);
            datas.add(tableBean);
        }

        model.addAttribute("headers",headers);
        model.addAttribute("datas",datas);
        return "table/table-bean";
    }

    @RequestMapping("/file-bean")
    public String fileBean(
            Model model,
            @RequestParam("name") String name,
            @RequestParam(value = "cssIndex",defaultValue = "1") Integer cssIndex
    ) throws IOException {
        Path path = Paths.get(ROOT,name);
        List<String> lines = Files.readAllLines(path);
        boolean first = true;
        List<String> headers = null;
        LinkedList<TableBean> datas = new LinkedList<>();
        for (String line : lines){
            String[] parts = line.split("[：\t]+");
            if(first){
                headers = Arrays.asList(parts);
                first = false;
                continue;
            }
            TableBean tableBean = new TableBean();
            for(int i=0;i<parts.length;i++){
                TableBean.invokeMethod(i,tableBean,parts[i]);
            }
            datas.add(tableBean);
        }
        model.addAttribute("headers",headers);
        model.addAttribute("datas",datas);
        model.addAttribute("cssIndex",cssIndex);
        return "table/table-bean";
    }



}
